#!/usr/bin/env php
<?php
require_once(__DIR__ . '/fun.php');
renderMonitor();

if ( islock() ) {
	
	$path = sys_get_temp_dir() . "/scale.lock";
	echo $path . "\n";

	echo "任务执行中...\n";
	return;	
}

// $cvmid = createCvm();
// if( $cvmid !== false ) {
// 	$resp = bindtoLB($cvmid);
// 	echo "成功\n";
// 	exit;
// }

$cvms = getBackends();
echo "线上设备总数: {$cvms['TotalCount']} \n";
foreach ($cvms['InstanceSet'] as $cvm ) {
	
	$id = $cvm['InstanceId'];
	$traffic = getTraffic($id);
	echo "{$id} 1分钟内网入包量 {$traffic['data']}   Min={$config['Min']} Max={$config['Max']} ...\n";
	// print_r($traffic);

	if ( $traffic['data'] > $config['Max'] && $cvms['TotalCount'] < 10 ) {
		echo "\t增加节点 ... ";
		$cvmid = createCvm();
		if( $cvmid !== false ) {
			$resp = bindtoLB($cvmid);
			echo "成功\n";
			exit;
		}
		echo "失败\n";
		break;
	}

	if ( $traffic['data'] < $config['Min'] && $cvms['TotalCount'] > 1 ) {
		echo "\t减少节点 ... \n";
		$resp = removeFromLB( $id );
		if ( $resp !== false ) {
			destoryCvm( $id );
		}
		break;
	}
}